// 值得参看 思维难度不大
#include <bits/stdc++.h>
using namespace std;
#define int long long
/*

我们的目标是减小c之和
枚举b，发现要么取a中最小的，要么取 ai= m+c -bi ,即ai中大于等于m-bi的
两者比较取min
a的元素考虑使用multiset维护显然，这样局部贪心能获得最优解
*/

void solve() {
  int n, m;
  cin >> n >> m;
  vector<int> a(n + 1);
  vector<int> b(n + 1);
  for (int i = 1; i <= n; i++)
    cin >> a[i];

  for (int i = 1; i <= n; i++)
    cin >> b[i];

  multiset<int> at;
  for (int i = 1; i <= n; i++)
    at.insert(a[i]);

  sort(a.begin() + 1, a.end());

  int ans = 0;
  for (int i = 1; i <= n; i++) {
    int res = (b[i] + *(at.begin())) % m;

    auto it = at.lower_bound(m - b[i]);
    if (it != at.end()) {
      int res2 = (b[i] + *(it)) % m;

      if (res2 < res) {
        at.erase(it);
        ans += res2;
      } else {
        at.erase(at.begin());
        ans += res;
      }
    } else {
      at.erase(at.begin());
      ans += res;
    }
  }
  cout << ans << endl;
}
signed main() {
  int T;
  cin >> T;
  while (T--) {
    solve();
  }
  return 0;
}